//
//  Process.m
//  CarTown
//
//  Created by xionghao on 15/9/9.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "Process.h"
#import <MJExtension.h>
#import "AppDelegate.h"

@implementation Process

@dynamic p_name;
@dynamic time;
+(void)addProcess:(NSArray *)data{
    AppDelegate *delegate=[[UIApplication sharedApplication]delegate];
    NSFetchRequest *request=[NSFetchRequest fetchRequestWithEntityName:@"Process"];
    NSArray *sets= [delegate.managedObjectContext executeFetchRequest:request error:nil];
    if (sets.count>0) {
        Process *area= sets[0];
        NSTimeInterval secondsInterval= [area.time timeIntervalSinceDate:[NSDate date]];
        if ([area.time isYesterday]||secondsInterval>24*60*60) {
            for (Process *a in sets) {
                [delegate.managedObjectContext deleteObject:a];
            }
            
            for (NSDictionary *dict in data) {
                Process *area=[NSEntityDescription insertNewObjectForEntityForName:@"Process" inManagedObjectContext:delegate.managedObjectContext];
                [area setValue:dict[@"p_name"] forKey:@"p_name"];
                [area setValue:[NSDate date] forKey:@"time"];
                [delegate saveContext];
            }
            
        }
        
    }else{
        for (NSDictionary *dict in data) {
            Process *a=[NSEntityDescription insertNewObjectForEntityForName:@"Process" inManagedObjectContext:delegate.managedObjectContext];
            [a setValue:dict[@"p_name"] forKey:@"p_name"];
            [a setValue:[NSDate date] forKey:@"time"];
            [delegate saveContext];
        }
        
    }

}
+(NSArray *)getProcess{
    AppDelegate *delegate=[[UIApplication sharedApplication]delegate];
    NSFetchRequest *request=[NSFetchRequest fetchRequestWithEntityName:@"Process"];
    NSSortDescriptor *sort=[NSSortDescriptor sortDescriptorWithKey:@"p_name" ascending:YES];
    request.sortDescriptors=@[sort];
    NSArray *sets= [delegate.managedObjectContext executeFetchRequest:request error:nil];
    return sets;

}
@end
